package cn.myschool.web;

import cn.myschool.entity.Student;
import cn.myschool.pojo.AjaxPage;
import cn.myschool.pojo.AjaxResult;
import cn.myschool.pojo.Page;
import cn.myschool.service.GradeService;
import cn.myschool.service.StudentService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("student")
public class StudentController {

    //private StudentService adminService= SpringUtil.getBean(StudentService.class);
    @Resource
    private StudentService studentService;//= SpringUtil.getBean(StudentService.class);
    @Resource
    private GradeService gradeService;

    @GetMapping("toAdd")
    public String toadd(Model m) {
        m.addAttribute("grades", gradeService.findALL());
        return "addStudent";
    }

    @GetMapping("search")
    public ModelAndView search(@RequestParam(name = "sname", required = false) String sname, @RequestParam(name = "qq", required = false) String qq, @RequestParam(name = "wechat", required = false) String wechat,
                               @RequestParam(name = "dateStart", required = false) Date start,
                               @RequestParam(name = "dateEnd", required = false) Date end,
                               @RequestParam(name = "pageNo", defaultValue = "1") int page) {
        Page<Student> search = studentService.search(wechat, qq, sname, start, end, page);
        ModelAndView mv = new ModelAndView();
        mv.addObject("p", search);
        mv.addObject("sname", sname);
        mv.addObject("qq", qq);
        mv.addObject("wechat", wechat);
        mv.addObject("dateStart", start);
        mv.addObject("dateEnd", end);
        //mv.setViewName("/WEB-INF/JSPS/student.jsp");
        mv.setViewName("student");
        return mv;
    }

    public void test( int id,HttpServletRequest request){
        //request.getReader().lines()
    }

    @GetMapping("ajaxsearch")
    @ResponseBody
    public Page<Student> ajaxsearch(@RequestParam(name = "sname", required = false) String sname, @RequestParam(name = "qq", required = false) String qq, @RequestParam(name = "wechat", required = false) String wechat,
                               @RequestParam(name = "dateStart", required = false) Date start,
                               @RequestParam(name = "dateEnd", required = false) Date end,
                               @RequestParam(name = "pageNo", defaultValue = "1") int page) {
        Page<Student> search = studentService.search(wechat, qq, sname, start, end, page);

        return  search;
    }
    @GetMapping("ajaxsearch2")
    @ResponseBody
    public AjaxPage<Student> ajaxsearch2(@RequestParam(name = "sname", required = false) String sname, @RequestParam(name = "qq", required = false) String qq, @RequestParam(name = "wechat", required = false) String wechat,
                                         @RequestParam(name = "dateStart", required = false) Date start,
                                         @RequestParam(name = "dateEnd", required = false) Date end,
                                         @RequestParam(name = "page", defaultValue = "1") int page) {
        Page<Student> p = studentService.search(wechat, qq, sname, start, end, page);

        return  new AjaxPage<>(p.getPageNo(),p.getTotalElements(),p.getDatas());
    }

//    @PostMapping("add")
//    public String add(@ModelAttribute("stu") Student student, HttpSession s) {
//        System.out.println(">>>>>>>>>>>>>>>>>" + student);
//        int add = this.studentService.add(student);
//        if (add > 0) {
//           s.setAttribute("msg","新生注册成功");
//            return "redirect:search";
//            //return "redirect:/ssm/student/search";
//        }
//        return "forward:/addSucess.jsp";//脱离视图解析器的约束
//        // return "addSucess";//移动过去
//    }
@PostMapping("add")
public String add(@ModelAttribute("stu") Student student, RedirectAttributes s, @RequestParam(name = "shenfenzheng",required = false) MultipartFile m, HttpServletRequest req) {

     if(!m.isEmpty()){
         //m.getName()
         ServletContext application = req.getServletContext();
         String images = application.getRealPath("images");
         File f=new File(images);
         if(!f.exists())
             f.mkdirs();

         String oldName=m.getOriginalFilename();
         String houzhui=oldName.substring( oldName.lastIndexOf('.'));
         String newName= UUID.randomUUID()+houzhui;
         try {
             m.transferTo(new File(f,newName));
             student.setIdcardpic("images/"+newName);
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
    int add = this.studentService.add(student);
    if (add > 0) {
        s.addAttribute("msg","新生 "+student.getSname()+"注册成功");
        return "redirect:search";
        //return "redirect:/ssm/student/search";
    }
    return "forward:/addSucess.jsp";//脱离视图解析器的约束
    // return "addSucess";//移动过去
}
    @PostMapping(value = "ajaxadd", produces ="application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult add2(Student student,  @RequestPart(name="file",required = false) MultipartFile m, HttpServletRequest req) {
        System.out.println(m+">>>>>>>>>>>>>>>>>>");
        if(!m.isEmpty()){
            //m.getName()
            ServletContext application = req.getServletContext();
            String images = application.getRealPath("/images");
            File f=new File(images);
            if(!f.exists())
                f.mkdirs();

            String oldName=m.getOriginalFilename();
            String houzhui=oldName.substring( oldName.lastIndexOf('.'));
            String newName= UUID.randomUUID()+houzhui;
            try {
                m.transferTo(new File(f,newName));
                student.setIdcardpic("images/"+newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = this.studentService.add(student);
        if (add > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
//public String add(@ModelAttribute("stu") Student student, RedirectAttributes s) {
//    System.out.println(">>>>>>>>>>>>>>>>>" + student);
//    int add = this.studentService.add(student);
//    if (add > 0) {
//        s.addAttribute("msg","新生 "+student.getSname()+"注册成功");
//        return "redirect:search";
//        //return "redirect:/ssm/student/search";
//    }
//    return "forward:/addSucess.jsp";//脱离视图解析器的约束
//    // return "addSucess";//移动过去
//}
    @GetMapping("del-{stuno}")
    public String del(@PathVariable("stuno") long stuno, RedirectAttributes s) {
        int del = this.studentService.del(stuno);
        s.addAttribute("msg",del>0?"删除成功":"删除失败");
        return "redirect:/student/search";
        //return "redirect:search";
        //return "forward:/addSucess.jsp";//脱离视图解析器的约束
        // return "addSucess";//移动过去
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值

        //第二个参数是特定的属性名称
        //binder.registerCustomEditor(Date.class,"examdate",new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
    }

}
